import 'package:flutter/material.dart';

class AnimateApp extends StatefulWidget {
  const AnimateApp({super.key});
  @override
  State<AnimateApp> createState() => _AnimateAppState();
}

class _AnimateAppState extends State<AnimateApp> with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> animation;
  @override
  void initState() {
    super.initState();
    //创建动画周期为1秒的AnimationController对象
    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 1000));
    //创建一条震荡曲线
    final CurvedAnimation curve = CurvedAnimation(
        parent: controller, curve: Curves.elasticOut);
    // 创建从50到200线性变化的Animation对象
    animation = Tween(begin: 50.0, end: 200.0).animate(curve);
      // ..addListener(() {
      //   setState(() {}); //刷新界面
      // });
    // 如果使用AnimatedWidget就可以省去上面的代码

    // 循环执行动画
    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        controller.reverse();//动画结束时反向执行
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();//动画反向执行完毕时，重新执行
      }
    });

    controller.forward(); //启动动画
  }

  @override
  Widget build(BuildContext context) {
    // return MaterialApp(
    //     home: Center(
    //         child: SizedBox(
    //             width: animation.value, // 将动画的值赋给widget的宽高
    //             height: animation.value,
    //             child: const FlutterLogo()
    //         )));
    // return AnimatedLogo(key: const Key('1'), animation: animation);
    return Center(
      child: AnimatedBuilder(
          animation: animation,//传入动画对象
          child: const FlutterLogo(),
          //动画构建回调
          builder: (context, child) => SizedBox(
            width: animation.value,//使用动画的当前状态更新UI
            height: animation.value,
            child: child, //child参数即FlutterLogo()
          )
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose(); // 释放资源
    super.dispose();
  }
}

class AnimatedLogo extends AnimatedWidget {
  //AnimatedWidget需要在初始化时传入animation对象
  const AnimatedLogo({required Key key, required Animation<double> animation})
      : super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    //取出动画对象
    final Animation<double> animation = listenable as Animation<double>;
    return Center(
        child: SizedBox(
          height: animation.value,//根据动画对象的当前状态更新宽高
          width: animation.value,
          child: const FlutterLogo(),
        ));
  }
}
